(function () {
    function debounce(fn, wait) {
        var timer = null;
        return function (e) {
            if (timer !== null) {
                clearTimeout(timer);
            }
            timer = setTimeout(function () {
                fn.call(this, e);
            }, wait);
        };
    }



    function throttle(func, wait) {
        //之前的时间戳
        let old = 0;
        return function () {
            //获取当前的时间戳
            let now = new Date().valueOf();
            if (now - old > wait) {
                //立即执行
                func.apply(this, arguments);

                old = now;
            }
        };
    }

    //更新积木块
    function editBlock(URL, settings, callback) {
        $.ajax({
            url: URL,
            type: "post",
            dataType: "json",
            headers: {
                "Content-Type": "application/json;charset=UTF-8"
            },
            data: JSON.stringify(settings),
            complete: function (e) {
                if (e.status === 200) {
                    callback && callback.call(this, e.responseText);
                } else {
                    alert("更新积木块失败");
                }
            }
        });
    }
    const throttleEditBlock = throttle(editBlock, 500);

    function message(e) {
        var messageData = JSON.parse(JSON.stringify(e.data));
        if (!messageData || !messageData.type) {
            return false;
        }
        console.log("接受数据", messageData, e);

        const blockNode = $("#oemsaas-section-" + messageData.id);

        const mainContent = $("#MainContent");

        let _addBtn = $("#oemsaas-add-btn");

        const _body = $("html,body");

        const addHtml = `<div class="oemsaas-add" id='oemsaas-add-btn'>点击右侧卡片添加到这里</div>`;

        //获取排序后的html
        function sortAllHtml(sortIds) {
            var html = "";
            for (let i = 0; i < sortIds.length; i++) {
                const id = sortIds[i];
                const outerHTML = $("#oemsaas-section-" + id).prop("outerHTML");
                if (outerHTML) {
                    html += $("#oemsaas-section-" + id).prop("outerHTML");
                }
            }
            return html;
        }

        
            //重新绑定a标题
        function hrefRedirect(node){
            node.find('a').click(function(e) {
                e.preventDefault();
                moi.href($(this).attr("href"))
            })
        }

        //定位当前编辑元素
        function positionCurrent(id, isLazy) {


            // 删除添加dom
            _addBtn && _addBtn.remove();

            //设置back
            if(document.referrer === "" || document.referrer.indexOf(location.host+'/admin') > -1 || moi.getUrlParam("theme_id")){
                $(".back-box").hide()
            }

            //设置商品图片大小
            if(window.productSize){
                window.productSize && productSize($(".product_img"));
            }

            //获取定位元素
            let positionNode = $(`#oemsaas-section-${id}`);
            if (messageData.block_type === "header" || messageData.block_type === "footer") {
                positionNode = $(`#card-${messageData.block_type}`);
            }

            //图片懒加载
            if (window.addLazyImages) {
                addLazyImages(positionNode.find("img[data-src]"));
            }

            //获取上传缓存的积木块id 如果和当前id一样不定位
            const oldBlockId = sessionStorage.getItem("blockId");
            if (oldBlockId && Number(oldBlockId) === id) {
                return false;
            }

            sessionStorage.setItem("blockId", messageData.id);

            if (id && positionNode.length) {
                animateScrollTop(positionNode);
            }

        }

        //元素滚到到指定位置
        function animateScrollTop(node) {
            const nodeTop = node.offset().top - 20;

            _body.stop().animate({ scrollTop: nodeTop }, 800, "linear", function () {
                // window.waterfallsScrollLoad = true;
                if (_body.scrollTop() < nodeTop) {
                    _body.stop().animate({ scrollTop: node.offset().top }, 400, "linear");
                }
            });
        }

        //追加删除元素
        function addDelNode() {
            if (!_addBtn.length) {
                mainContent.append(addHtml);
                _addBtn = $("#oemsaas-add-btn");
                animateScrollTop(_addBtn);
                sessionStorage.removeItem("blockId");//清楚缓存id
            }
        }

        if (messageData.id && messageData.settings) {
            //设置积木块id
            messageData.settings["block_id"] = messageData.id || new Date().getTime();
            //获取页面存储id
            messageData.settings["page_id"] = moi.getPageStorage("page_id") || messageData.settings.page_id;

            //获取缓存参数、方便积木块渲染显示
            messageData.settings["params"] = moi.getPageStorage("messageParams");

            //获取缓存参数、方便积木块渲染显示
            if (themeConfig) {
                messageData.settings["theme_config"] = themeConfig;
            }
            //设置积木块类型
            messageData.settings["type"] = messageData.block_type;

            //当前页面路由
            messageData.settings["router"] = window.oemcart_current_router || "";
            messageData.settings["router_handle"] = window.oemcart_current_route_handle || "";
        }

        switch (messageData.type) {
            // 全局设置 刷新页面
            case "global":
                location.reload();
                break;
            //排序
            case "sort":
                // mainContent.html(sortAllHtml(messageData.sortIds));
                // setTimeout(() => {
                //     positionCurrent(messageData.id);
                // }, 500);
                location.reload();
                break;
            //改变积木块
            case "block":
                moi.onEvent("updateBlock",{messageData});
                let themeId =  moi.getUrlParam('theme_id')
                let themeIdParms = themeId ? `?theme_id=${themeId}&page_ca=${window.oemcart_page_ca || ""}` : ''
                var URL = `/block/type/${messageData.block_type}${themeIdParms}`

                throttleEditBlock(URL, messageData.settings, function (html) {
                    if (messageData.block_type === "header" || messageData.block_type === "footer") {
                        const node = $(`#card-${messageData.block_type}`);
                        node.html(html);
                        positionCurrent(messageData.id, false);
                        return;
                    }
                    blockNode.html(html);
                        //出发渲染事件
                    const event = new CustomEvent("DOMContentLoaded",{detail:{eventBlockName:messageData.block_type}});
                    document.dispatchEvent(event);
                    positionCurrent(messageData.id, true);
                });
                break;
            //积木块定位
            case "position":
                moi.onEvent("positionBlock",{messageData});
                messageData.id ? positionCurrent(messageData.id) : addDelNode();
                break;
            //删除积木块
            case "del":
                moi.onEvent("delBlock",{messageData});
                $("#oemsaas-section-" + messageData.delId).remove();
                //messageData.id ? positionCurrent(messageData.id) :
                addDelNode();
                break;
            //添加块定位
            case "add":{ //加大括号原因是用了let case下面有相同的变量要报错的问题
                
                moi.onEvent("addBlock",{messageData});
                let themeId =  moi.getUrlParam('theme_id')
                let themeIdParms = themeId ? `?theme_id=${themeId}&page_ca=${window.oemcart_page_ca || ""}` : ''
                var URL = `/block/type/${messageData.block_type}${themeIdParms}`
                throttleEditBlock(URL, messageData.settings, function (html) {
                    const newblockHtml = `<div id="oemsaas-section-${messageData.id}" data-section-type="${messageData.block_type}" data-section-id="${messageData.id}">${html}</div>`;
                    mainContent.append(newblockHtml);
                    positionCurrent(messageData.id, true);
                    //出发渲染事件
                    const event = new CustomEvent("DOMContentLoaded",{detail:{eventBlockName:messageData.block_type}});
                    document.dispatchEvent(event);
                });
                break;   
            }
        }
    }

    //监听消息
    window.onmessage = message;

    //加载完成发送消息给父页面
    window.parent.postMessage({ type: "load", current_router: oemcart_current_router, current_router_handle: oemcart_current_route_handle, href: decodeURIComponent(window.location.href) }, "*");

    //页面卸载监听
    window.addEventListener("beforeunload", function (e) {
        console.log('卸载通知')
        sessionStorage.removeItem("blockId");
        window.parent.postMessage({ type: "unload", current_router: oemcart_current_router, current_router_handle: oemcart_current_route_handle, href: decodeURIComponent(window.location.href) }, "*");
        return false;
    });
    
})();
//
